<template>
   <div class="app-container">
     <!-- 查询条件开始 -->
     <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          size="small"
          style="width:240px"
        />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleCode">
        <el-input
          v-model="queryParams.roleCode"
          placeholder="请输入权限字符"
          clearable
          size="small"
          style="width:240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="可用状态"
          clearable
          size="small"
          style="width:240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width:240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholde="开始日期"
          end-placeholde="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

     <!-- 查询条件结束 -->

     <!-- 表头按钮开始 -->
     <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
       <el-col :span="1.5">
        <el-button type="warning  " icon="el-icon-thumb" size="mini" :disabled="single" @click="handleSelectMenu">分配权限</el-button>
      </el-col>
    </el-row>

     <!-- 表头按钮结束 -->
     <!-- 表格数据开始 -->
     <el-table v-loading="loading" border :data="roleTableList" @selection-change="handleSelectionChnage">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="角色ID" align="center" prop="roleId" />
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <el-table-column label="权限编码" align="center" prop="roleCode" />
      <el-table-column label="显示顺序" align="center" prop="roleSort" />
      <el-table-column label="状态" prop="status" align="center" :formatter="statusFormatter" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" width="280">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          <el-button  type="text" icon="el-icon-thumb" size="mini" @click="handleSelectMenu(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

     <!-- 表格数据结束 -->

     <!--分页组件开始-->
      <el-pagination
      v-show="total>0"
      :current-page="queryParams.pageNum"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
     <!--分页组件结束-->
     <!-- 添加修改弹出层开始 -->
     <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      center
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" clearable size="small" />
        </el-form-item>
        <el-form-item label="权限编码" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入权限字符" clearable size="small" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" clearable size="small" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              :value="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入字典备注" clearable size="small" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>

     <!-- 添加修改弹出层结束 -->
     <!--分配权限弹出层开始-->
     <el-dialog
     :title="title"
     :visible.sync="selectMenuOpen"
     width="400px"
     :before-close="handleClose"
     center
     append-to-body
     >
      <el-tree
       ref="tree"
      :data="selectMenuTreeData"
      show-checkbox
      node-key="menuId"
      :props="defaultProps"
       />
     <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSelectMenuSubmit">确 定</el-button>
        <el-button @click="cancelSelectMenu">取 消</el-button>
      </span>
     </el-dialog>
     
     <!-- 分配权限弹出层结束-->
     </div>
</template>
<script>
import {listRoleForPage,getRoleById,addRole,updateRole,deleteRoleByIds,saveRoleMenu} from '@/api/system/role'
import {selectMenuTree,getMenuIdsByRoleId} from '@/api/system/menu'
export default {
  data(){
    return {
      //遮罩
      loading:false,
      //表格数据
      roleTableList:[],
      //数量
      total:0,
      //标题
      title:'',
      //日期
      dateRange:[],
      //状态
      statusOptions:[],
      //查询参数
      queryParams:{
        pageNum:1,
        pageSize:10,
        status:undefined,
        roleCode:undefined,
        roleName:undefined,
      },
      //表格选中的几个
      ids:[],
      //非单选禁用
      single:true,
      //非多选禁用,
      multiple:true,
      //添加修改表单
      form:{},
      //弹出层
      open:false,
      //表单校验
      rules:{
        roleName:[
          { required: true, message: '角色名称不能为空', trigger: 'blur'}
        ],
        roleCode:[
          { required: true, message: '权限编码不能为空', trigger: 'blur'}
        ],

        },
      //分配权限是否打开
      selectMenuOpen:false,
      selectMenuTreeData:[],
      defaultProps:{
            id:'menuId',
           children: 'children',
           label: 'menuName'
      },
      //当前选中角色
      currentRoleId:undefined

    }
  },
  //钩子
  created(){
    //状态数据字典
    this.getDataByType("sys_normal_disable").then(res =>{
      this.statusOptions = res.data
    })
    //查询表格数据
    this.getListRoleForPage()

  },
  methods: {
    //查询表格数据
    getListRoleForPage(){
      this.loading = true
      listRoleForPage(this.addDateRange(this.queryParams,this.dateRange)).then(res => {
          this.roleTableList = res.data
          this.total = res.total
          this.loading = false
      })

    },
    //分页页大小发生改变
    handleSizeChange(val){
        this.queryParams.pageSize = val
        this.getListRoleForPage()
    },
    handleCurrentChange(val){
        this.queryParams.pageNum = val; 
         this.getListRoleForPage()
    },
    //搜索
    handleQuery(){
      this.getListRoleForPage()
    },
    //重置
    resetQuery(){
      this.resetForm('queryForm')
      this.dateRange=[]
      this.queryParams.pageNum=1
      this.queryParams.pageSize=10
      this.getListRoleForPage()
    },
    //新增
    handleAdd(){
      this.title= "添加角色信息"
      this.reset()
      this.open = true

    },
    //修改
    handleUpdate(row){
      this.title= "修改角色信息"
      this.reset()
      let roleId = row.roleId === undefined ? this.ids[0] : row.roleId
      getRoleById(roleId).then(res =>{
        this.form = res.data
        this.open = true
      })
    },
    //删除
    handleDelete(row){
      let roleIds = row.roleId === undefined ? this.ids :row.roleId
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            deleteRoleByIds(roleIds).then(res =>{
            this.msgSuccess('删除成功')
            this.getListRoleForPage()
      })
        }).catch(() => {
          this.msgInfo('删除已取消')
         this.getListRoleForPage()
        });

    },
    //分配权限
    handleSelectMenu(row){
      this.title = "分配权限"
      let roleId = row.roleId ===undefined?this.ids[0]:row.roleId
      this.currentRoleId = roleId
      selectMenuTree().then(res =>{
        this.selectMenuTreeData = this.handleTree(res.data,'menuId')
        getMenuIdsByRoleId(roleId).then(res =>{
          this.$refs.tree.setCheckedKeys(res.data)
        })
         this.selectMenuOpen=true
      })
    },
    //表格多选框选中事件
    handleSelectionChnage(selection){
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length!=1   
      this.multiple = !selection.length!=0  
    },
    //状态翻译
    statusFormatter(row){
      return this.selectDictLabel(this.statusOptions,row.status)
    },
    //提交
    handleSubmit(){
      this.$refs['form'].validate((valid) => {
          if (valid) {
      //ture 添加
      if(this.form.roleId === undefined){
          addRole(this.form).then(res =>{
            this.msgSuccess('保存成功')
            this.open = false
            this.getListRoleForPage()
          })
      }else{
        updateRole(this.form).then(res =>{
          this.msgSuccess('修改成功')
            this.open = false
            this.getListRoleForPage()
        })
      }
      }
      })
    },
    //取消
    cancel(){
      this.open = false
      

    },
    //重置
    reset(){
       this.form = {
        roleId:undefined,
        roleCode:undefined,
        roleName:undefined,
        roleSort:'0',
        status:'0',
        remark:undefined,
      }
      this.resetForm('form')
    },
    //保存权限
    handleSelectMenuSubmit(){
      //获取全选的key
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      //console.log('全选key'+checkedKeys)
      //获取半选的key
      const HalfcheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      // console.log('半选key'+HalfcheckedKeys)
      //最终key
      // const lastKeys = checkedKeys.concat(HalfcheckedKeys)
      const lastKeys= [...checkedKeys,...HalfcheckedKeys]
      //console.log('最终key'+lastKeys)
      saveRoleMenu(this.currentRoleId,lastKeys).then(res =>{
          this.msgSuccess("分配成功")
          getMenuIdsByRoleId(this.currentRoleId).then(res =>{
          this.$refs.tree.setCheckedKeys(res.data)
        })
      })
    },
    //取消保存权限
    cancelSelectMenu(){
        this.selectMenuOpen=false 
        this.selectMenuTreeData = []
        this.$refs.tree.setCheckedKeys([]);
    },
    //关闭取消勾选权限
    handleClose(done){
      this.$refs.tree.setCheckedKeys([]);
      done()
    }
    
  },
  watch:{
    'queryParams.status':{
      handler(val,old){
        this.queryParams.pageNum = 1
        this.getListRoleForPage()
      },
      deep:true
    },
    'queryParams.roleCode':{
      handler(val,old){
        this.queryParams.pageNum = 1
        this.getListRoleForPage()
      },
      deep:true
    },
    'queryParams.roleName':{
      handler(val,old){
        this.queryParams.pageNum = 1
        this.getListRoleForPage()
      },
      deep:true
    },
    'dateRange':{
        handler(val,old){
        this.queryParams.pageNum = 1
        this.getListRoleForPage()
      },
      deep:true
    }
  }
  
}
</script>